#ifndef TMSGMNG_H
#define TMSGMNG_H

#ifndef STRICT
#define STRICT
#endif



#include <windows.h>
#include "common_include.h"
#include "MsgBuf.h"
#include "cfg.h"

class MsgMng {
protected:
	SOCKET		udp_sd;
	SOCKET		tcp_sd;

	BOOL		status;
	ULONG		packetNo;
	Cfg			*cfg;

	HWND		hAsyncWnd;
	UINT		uAsyncMsg;
	UINT		lAsyncMode;
	HostSub		local;

	BOOL		WSockInit(BOOL recv_flg);
	void		WSockTerm(void);
	BOOL		WSockReset(void);

public:
	MsgMng(ULONG nicAddr, int portNo, Cfg *cfg=NULL);
	~MsgMng();

	BOOL	GetStatus(void)	{ return	status; }
	HostSub	*GetLocalHost(void) { return	&local; }
	void	CloseSocket(void);
	BOOL	IsAvailableTCP() { return tcp_sd != INVALID_SOCKET ? TRUE : FALSE; }

	BOOL	Send(HostSub *hostSub, ULONG command, int val);
	BOOL	Send(HostSub *hostSub, ULONG command, const char *message=NULL, const char *exMsg=NULL);
	BOOL	Send(ULONG host_addr, int port_no, ULONG command, const char *message=NULL, const char *exMsg=NULL);
	BOOL	AsyncSelectRegist(HWND hWnd);
	BOOL	Recv(MsgBuf *msg);
	BOOL	ResolveMsg(RecvBuf *buf, MsgBuf *msg);
	ULONG	MakePacketNo(void) { return packetNo++; }
	ULONG	MakeMsg(char *udp_msg, int packetNo, ULONG command, const char *msg, const char *exMsg=NULL, int *packet_len=NULL);
	ULONG	MakeMsg(char *udp_msg, ULONG command, const char *msg, const char *exMsg=NULL, int *packet_len=NULL) { return	MakeMsg(udp_msg, MakePacketNo(), command, msg, exMsg, packet_len); }
	BOOL	UdpSend(ULONG host_addr, int port_no, const char *udp_msg);
	BOOL	UdpSend(ULONG host_addr, int port_no, const char *udp_msg, int len);
	BOOL	UdpRecv(RecvBuf *buf);

	BOOL	Accept(HWND hWnd, ConnectInfo *info);
	BOOL	Connect(HWND hWnd, ConnectInfo *info);
	BOOL	AsyncSelectConnect(HWND hWnd, ConnectInfo *info);
	BOOL	ConnectDone(HWND hWnd, ConnectInfo *info);

	static int LocalNewLineToUnix(const char *src, char *dest, int maxlen);
	static int UnixNewLineToLocal(const char *src, char *dest, int maxlen);
};

#endif